<template>
  <page-wrap back hideSafeArea title="小览" needLogin navLeft hideTab :showTop="true" txtColor='#000' bgColor="#fff"
    ref="pageWrap">
    <view class="content">
      <!-- 聊天内容 -->
      <scroll-view @touchstart="closeMore" :class="{'chat':true, 'chat-main':true,'android-chat':!isIOS}"
        :scroll-y="true" :enable-flex="true" scroll-with-animation="true" :scroll-into-view="scrollToViewSelector"
        @scrolltoupper="loadMore" :upper-threshold='20'>
        <view class="usualProblemListContainer" v-if="usualProblemList.length">
          <view class="problemList">
            <p v-for="_item,_index in usualProblemList" :key="_index" @click="handleClickAbleLinkClick(_item)"
              class="clickAbleLink">
              <view class="dotContainer">
                <view class="problemDot"></view>
              </view>
              {{_item.title}}
            </p>
            <p class="reloadLinks" @click="handleReloadLinks">
              <view class="reloadIconContainer">
                <u-icon name="reload" color="#ff4500" size="28" />
              </view> 换一批
            </p>
          </view>
          <view class="refreshProblemButton"></view>
        </view>
        <u-loadmore v-if="(unshiftmsg.length || !loaded)&&moreLoading!='nomore'&&moreLoading!='loadmore'"
          class="list-more" :status="moreLoading" :load-text="loadText" />
        <view class="chat-ls" v-for="(item,index) in unshiftmsg" :key="index" :id="'msg'+ index">
          <view class="chat-time" v-if="item.createTime != ''">{{changeTime(item.createTime)}}</view>
          <view class="msg-m msg-left" v-if="item.role ==  'assistant'">
            <image class="user-img" src="https://img3.job1001.com/xiaolan/images/xiaolanIcon.png"></image>
            <view class="message" v-if="item.TextType == 0">
              <!-- 文字 -->
              <view class="msg-text">
                <text class="gptText" v-show="item.sendText" user-select="true">{{item.sendText}}</text>
              </view>
            </view>

            <view class="message" v-if="item.TextType == 50">
              <!-- 不计入消息记录的文字 -->
              <view class="msg-text">
                <text class="gptText" v-show="item.sendText" user-select="true">{{item.sendText}}</text>
              </view>
            </view>
            <view class="message" v-if="item.TextType == 1">
              <!-- 报告 -->
              <view class="msg-report">
                <template v-if="item.elanContent&&item.elanContent.length">
                  <view class="rank">
                    <!-- <p class="addonTips">同时，这是一览为您推荐的相关职业内容：</p> -->
                    <view class="rank-item" v-for="(_item, _index) in item.elanContent" :key="_index"
                      @click="handleToDetail(_item)">
                      <template>
                        <view class="reportItem">
                          <view class="rank-item-title u-line-2">
                            {{_item.activityName}}
                          </view>
                          <view class="rank-item-bottom">
                            <view class="rank-item-des u-line-2">
                              {{_item.activityIntroduce}}
                            </view>
                            <u-image class="rank-item-img" :src="_item.bannerUrl" width="78rpx" height="86rpx"
                              border-radius="8rpx"></u-image>
                          </view>
                        </view>
                      </template>
                    </view>
                  </view>
                </template>
              </view>
            </view>
            <view class="message" v-if="item.TextType == 2">
              <!-- 案例 -->
              <view class="msg-case">
                <template v-if="item.elanContent&&item.elanContent.length">
                  <view class="rank">
                    <!-- <p class="addonTips">同时，这是一览为您推荐的相关职业内容：</p> -->
                    <view class="rank-item" v-for="(_item, _index) in item.elanContent" :key="_index"
                      @click="handleToDetail(_item)">
                      <template>
                        <view class="reportItem">
                          <view class="rank-item-title u-line-2">
                            {{_item.activityName}}
                          </view>
                          <view class="rank-item-bottom">
                            <view class="rank-item-des u-line-2">
                              {{_item.activityIntroduce}}
                            </view>
                            <u-image class="rank-item-img" :src="_item.bannerUrl" width="78rpx" height="86rpx"
                              border-radius="8rpx"></u-image>
                          </view>
                        </view>
                      </template>
                    </view>
                  </view>
                </template>
              </view>
            </view>

            <!-- <view class="message" v-if="item.TextType == 1" @tap="previewImg(item.sendText)">
            
              <image :src="item.sendText" class="msg-img" mode="widthFix"></image>
            </view>
            <view class="message" v-if="item.TextType == 2" @tap="playVoice(item.sendText.voice)">
            
              <view class="msg-text voice" :style="{width:item.sendText.time*4+'rpx'}">
                <image src="../../../static/icon/Hotline.png" class="voice-img"></image>
                {{item.sendText.time}}″
              </view>
            </view> -->
            <view class="message" v-if="item.TextType == 3" @tap="openLocation(item.sendText)">
              <!-- 位置 -->
              <view class="msg-map">
                <view class="map-name">{{item.sendText.name}}</view>
                <view class="map-address">{{item.sendText.address}}</view>
                <!-- 如果map不起作用，就可以直接用一张图片去替代 -->
                <map class="map" :longitude="item.sendText.longitude" :latitude="item.sendText.latitude"
                  :markers="covers(item.sendText)"></map>
              </view>
            </view>
          </view>
          <view class="msg-m msg-right" v-if="item.role == 'user'">
            <img class="user-img" :src="avatar"></img>
            <view class="message" v-if="item.TextType == 0">
              <view class="msg-text" user-select="true">{{item.sendText}}</view>
            </view>
            <view class="message" v-if="item.TextType == 1" @tap="previewImg(item.sendText)">
              <image :src="item.sendText" class="msg-img" mode="widthFix"></image>
            </view>
            <view class="message" v-if="item.TextType == 2" @tap="playVoice(item.sendText.voice)">
              <!-- 音频 -->
              <view class="msg-text voice" :style="{width:item.sendText.time*4+'rpx'}">
                {{item.sendText.time}}″
                <image src="../../../static/icon/Hotline.png" class="voice-img"></image>
              </view>
            </view>
            <view class="message" v-if="item.TextType == 3" @tap="openLocation(item.sendText)">
              <!-- 位置 -->
              <view class="msg-map">
                <view class="map-name">{{item.sendText.name}}</view>
                <view class="map-address">{{item.sendText.address}}</view>
                <map class="map" :longitude="item.sendText.longitude" :latitude="item.sendText.latitude"
                  :markers="covers(item.sendText)"></map>
              </view>
            </view>
          </view>
        </view>
        <!--  垫底标签 -->
        <view class="lastView" id="lastView" :style="{height:1 +'px', width:100 +'px'}"></view>

      </scroll-view>
      <submit class="bottomSubmit" @send="inputs" :usualProblemList="allUsualProblemList" @heights="heights"
        @submitElementRect="submitElementRect" :loading="loading" @handleStop="handleStop" :connecting="connecting">
      </submit>
    </view>
  </page-wrap>

</template>

<script>
import dateTime from "./utils/dateTime.js";
import submit from "./submit.vue";
import WebsocketHeartbeat from "websocket-heartbeat-miniprogram";
import { getSearchList, getRandomDictData } from "@/api/modules/library";
import { reqAppAddBrowseRecord } from "@/api/modules/report";
import { getPersonDetail } from "@/api/index";
import { queryChatData, addChatData } from "@/api/modules/message";
import ShareMixin from "@/mixins/share";

//音频播放
// const innerAudioContext = uni.createInnerAudioContext();

export default {
  mixins: [ShareMixin],
  data() {
    return {
      msg: [],
      // 反转数据接收
      unshiftmsg: [], //TextType中0等于普通文本信息，1等于报告推荐信息，2等于案例推荐信息
      imgMsg: [],
      scrollTopHeight: "",
      old: {
        scrollTopHeight: "",
      },
      oldTime: new Date(),
      inputh: "60",
      inputAreaHeight: 0,
      inputAreaTop: 0,
      websock: "",
      sendKeywordTask: "",
      searchKeyword: "",
      socketOpen: false,
      loading: false,
      isStoped: false,
      isContinue: false,
      caseList: [],
      reportList: [],
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      userInfo: {},
      avatar: "",
      usualProblemList: [],
      allUsualProblemList: [],
      usualProblemPageNo: 1,
      defaultAvatar: this.$imgBase + "avatar.png",
      scrollToViewSelector: "",
      pageNo: 1,
      pageSize: 10,
      loadText: {
        loadmore: "加载更多",
        loading: "加载中",
      },
      moreLoading: "loadmore",
      isPageAdd: false,
      isIOS: uni.getSystemInfoSync().platform == "ios",
      shareTitle: "小览 - " + this.$selfName,
      sharePath: "/pagesSub/elanwBot/index",
      connecting: false,

      isCalculating: false,
      screenHeight: 0,
      recordLastMsgHeight: {
        preHeight: 0,
        newHeight: -1,
      },
    };
  },
  onReady() {
    let systemInfo = uni.getSystemInfoSync();
    this.screenHeight = systemInfo.windowHeight;
  },
  created() {
    this.getChatHistory();
    this.reqGetRandomDictData();
    this.reqUsualProblemByPage(false);
    this.getPersonDetail();
    this.initGptWebsocket();
    this.goBottom();
  },

  onShow() {},
  onHide() {
    this.loading = false;
    this.websock.close();
    this.sendKeywordTask.close();
  },
  onPageScroll(e) {
    console.log(e);
  },
  beforeDestroy() {
    uni.hideLoading();
    this.websock.close();
    this.sendKeywordTask.close();
    this.websock = null;
    this.sendKeywordTask = null;
  },
  activated() {
    if (!this.websock) {
      this.initGptWebsocket();
    }
    // 跳转到最后一条数据
    this.goBottom();
  },
  components: {
    submit,
  },
  watch: {
    unshiftmsg: {
      handler(val) {
        if (this.isPageAdd) {
          this.isPageAdd = false;
          return;
        }
        setTimeout(() => {
          this.scrollToViewSelector = "msg" + (val.length - 1);
          uni.pageScrollTo({
            selector: this.scrollToViewSelector,
            duration: 300,
          });
        }, 0);
      },
      immediate: true,
    },
  },
  methods: {
    loadMore() {
      if (this.moreLoading == "loading" || this.moreLoading == "nomore") return;

      this.getChatHistory(true);
    },
    getChatHistory() {
      const params = {
        personId: this.personId,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      this.moreLoading = "loading";
      console.log(params);
      queryChatData(params).then((res) => {
        console.log(res);
        this.moreLoading = "loadmore";
        if (res.code == 200) {
          //dataType 50报告60案例
          //TextType 1报告2案例
          const TextTypes = { 10: 0, 50: 1, 60: 2 };
          const chatHistory = res.data
            .map((item) => {
              if (item.dataType == 50 || item.dataType == 60) {
                var elanContent = JSON.parse(item.sendText);
              }
              return {
                ...item,
                TextType: TextTypes[item.dataType],
                elanContent,
              };
            })
            .reverse();
          if (this.unshiftmsg.length != 0) {
            this.isPageAdd = true;
          }
          this.unshiftmsg = chatHistory.concat(this.unshiftmsg);
          if (this.pageNo >= res.pageparam.pages) {
            this.moreLoading = "nomore";
          }
          this.pageNo++;
        }
        if (params.pageNo == 1) {
          this.goBottom();
        }
      });
    },
    uploadChatRecord(obj) {
      //dataType 10文本50报告60案例
      //TextType 0普通文本1报告2案例
      const dataTypes = [10, 50, 60, 40];
      let dataType = dataTypes[obj.TextType];
      let sendText = "";
      if (obj.TextType == 0) {
        sendText = obj.sendText;
      } else {
        sendText = JSON.stringify(obj.elanContent);
      }
      const params = {
        personId: this.personId,
        sendText,
        role: obj.role,
        createTime: obj.createTime,
        dataType,
      };
      addChatData(params).then((res) => {
        console.log(res);
      });
    },
    closeMore() {
      this.$bus.$emit("touchToCloseMore");
    },
    handleReloadLinks() {
      this.reqGetRandomDictData();
    },
    reqGetRandomDictData() {
      const params = {
        type: "CHAT_GPT_QUESTION",
        pageSize: 5,
        pageNo: this.usualProblemPageNo,
        num: 5,
      };
      console.log("getRandomDictData");
      console.log(params);
      getRandomDictData(params)
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.usualProblemList = res.data;
            if (
              res.pageparam &&
              res.pageparam.pages <= this.usualProblemPageNo
            ) {
              this.usualProblemPageNo = 1;
            } else {
              this.usualProblemPageNo += 1;
            }
          }
        })
        .finally(() => {
          //this.usualProblemPageNo += 1;
        });
    },

    // 分页获取 常见问题列表，目前数量较少，直接一次获取所有数据
    reqUsualProblemByPage(isMore) {
      const params = {
        type: "CHAT_GPT_QUESTION",
        pageSize: 100,
        pageNo: 1,
        num: 100,
      };
      console.log("reqUsualProblemByPage");
      console.log(params);
      getRandomDictData(params)
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            if (isMore) {
              this.allUsualProblemList.push(...res.data);
            } else {
              this.allUsualProblemList = res.data;
            }
          }
        })
        .finally(() => {});
    },

    getPersonDetail() {
      if (!getApp().globalData.userInfo || !getApp().globalData.userInfo.id) {
        let param = {
          param: JSON.stringify({
            personId: this.personId,
          }),
          where: "",
          slaveInfo: 1,
        };
        getPersonDetail(param).then((res) => {
          this.userInfo = res.data || res;
          this.avatar = this.userInfo.pic || defaultAvatar;
          // if (
          //   !this.userInfo.pic &&
          //   this.userInfo.pic.indexOf("img.job1001.com/myUpload/pic.gif") >= 0
          // ) {
          //   this.userInfo.pic = this.$defalutAvatar;
          // }
          getApp().globalData.userInfo = this.userInfo;
        });
      } else {
        this.userInfo = getApp().globalData.userInfo;
        this.avatar = this.userInfo.pic;
      }
    },

    // 检查当前问题是否是选中的常见问题，返回常见问题序号，否则返回 -1
    checkIsUsualProblem(content) {
      var length = this.allUsualProblemList.length;
      for (var i = 0; i < length; i++) {
        if (this.allUsualProblemList[i].title == content) {
          return i;
        }
      }
      return -1;
    },

    //接受输入内容
    inputs(e) {
      if (this.loading) {
        uni.showToast({ title: "请等待上一个问题回答完毕哦！", icon: "none" });
        return;
      }
      // 隐藏软键盘
      uni.hideKeyboard();

      //先推一个用户发送的
      let data = {
        role: "user",
        sendText: e.message,
        createTime: new Date(),
        updateTime: "",
        chatmState: 1,
        TextType: e.type,
      };
      this.unshiftmsg.push(data);
      this.uploadChatRecord(data);

      // 如果是常见问题，就返回设置好的答案
      let usualProblemIndex = this.checkIsUsualProblem(e.message);
      if (usualProblemIndex >= 0) {
        console.log("检查到是常见问题");
        let usualProblemAnswer = {
          role: "assistant",
          sendText: this.allUsualProblemList[usualProblemIndex].value,
          createTime: new Date(),
          updateTime: "",
          chatmState: 1,
          TextType: 0,
        };
        this.unshiftmsg.push(usualProblemAnswer);
        this.uploadChatRecord(usualProblemAnswer);
        return;
      }

      //处理上下文
      let context = [];
      this.unshiftmsg.forEach((item, index) => {
        if (!item.clickAbleLink && item.sendText) {
          let content = "";
          if (item.role == "user") {
            content = `假设你是一名资深的企业管理咨询顾问，时间很宝贵。如果有人问这个问题: “${item.sendText}”请你做出判断，如果这不直接属于企业管理咨询的问题，请回复“小览是企业成长顾问，你可以问我企业管理相关的问题，我在这方面更专业。”，中间不用做任何的分析；如果这是直接属于企业管理咨询的问题，请展开分析，开头使用“我是小览，企业成长顾问。”。`;
          } else {
            content = item.sendText;
          }
          context.push({
            role: item.role,
            content,
          });
        }
      });
      if (context.length >= 5) {
        context = context.slice(-4);
      }

      //发送
      this.websock.send({
        data: JSON.stringify({
          userName: this.userInfo.iname,
          userId: this.userInfo.id,
          messages: context,
        }),
        success: (res) => {
          console.log("消息发送成功了!");
          this.loading = true;
          //再建立一个ws问gpt问题中的职业词语；同时请求JAVA接口查询案例和报告
          this.handleGetKeywordByInputs(e.message);
          //时间间隔处理
          // this.goBottom();
          //然后再推一个机器人回复的

          let asistentData = {
            role: "assistant",
            sendText: "",
            createTime: new Date(),
            updateTime: "",
            chatmState: 1,
            TextType: 0,
          };
          this.unshiftmsg.push(asistentData);
        },
        fail: (err) => {
          // uni.showToast({
          //   title: "正在连接您的专属顾问服务",
          //   icon: "none",
          // });
          console.log("消息发送错误！断开重连", err);
          this.websock.close();
          setTimeout(() => {
            this.initGptWebsocket();
            console.log("this.initGptWebsocket", this.task);
          }, 2000);
        },
      });

      // if (e.type == 1) {
      //   this.imgMsg.push(e.message);
      // }
      // this.goBottom();
    },
    sendKeywordSearch(val) {
      setTimeout(() => {
        this.sendKeywordTask.send({
          data: JSON.stringify({
            userName: "",
            userId: "",
            stream: false,
            messages: [
              {
                role: "system",
                content: `仅提取问题中的职业名称。不需要回答问题。按特定格式返回如{"name":"java开发工程师"}`,
              },
              { role: "user", content: val },
            ],
          }),
          success: (res) => {
            console.log("询问关键词消息发送成功了!");
          },
          fail: (err) => {
            this.sendKeywordSearch(val);
            console.log("消息发送错误！", err);
          },
        });
      }, 3000);
    },
    handleGetKeywordByInputs(val) {
      WebsocketHeartbeat({
        miniprogram: wx,
        connectSocketParams: {
          url: "wss://chatgpt.yl1001.com",
        },
        repeatLimit: 20,

        pingTimeout: 150000,
      }).then((task) => {
        this.sendKeywordTask = task;
        task.onOpen = (e) => {
          //钩子函数
          console.log("askSocketTask open");
        };
        task.onClose = (e) => {
          //钩子函数
          console.log("askSocketTask close");
        };
        task.onError = (e) => {
          //钩子函数
          task.close({
            success(res) {
              console.log("ws错误，关闭此连接！", res);
            },
          });
          console.log("askSocketTask onError：", e);
        };
        task.onMessage = (data) => {
          //钩子函数
          const res = JSON.parse(data.data);
          if (res.choices.length && res.choices[0].message) {
            const obj = res.choices[0].message.content;

            try {
              var searchKeyword = JSON.parse(obj).name;
            } catch (error) {
              console.log("error", error);
              task.close();
              return;
            }

            this.getReportAndCaseData(searchKeyword);
            //完成之后关闭这个问的ws
            task.close();
          }
        };
        task.onReconnect = () => {
          //钩子函数
          console.log("askSocketTask reconnect...");
        };
        task.socketTask.onOpen((e) => {
          //原生实例注册函数，重连后丢失
          console.log("askSocketTask open");
        });
        task.socketTask.onMessage((data) => {
          //原生实例注册函数，重连后丢失
          console.log("askSocketTask data");
        });
        this.sendKeywordSearch(val);
      });
    },
    async getReportAndCaseData(keyword) {
      const reportParams = {
        keyword: keyword,
        pageNo: 1,
        pageSize: 5,
        activityTypeCode: "CAREER_REPORT",
      };
      const caseParams = {
        keyword: keyword,
        pageNo: 1,
        pageSize: 5,
        activityTypeCode: "CAREER_CASE",
      };
      // getSearchList(params).then((res) => {
      //   if (res.code == 200) {
      //     //先存起来，等chatGPT发送的信息状态为done的时候再加到对象里
      //     this.elanContentTemp = res.data;
      //   }
      // });
      const [reportResult, caseResult] = await Promise.allSettled([
        getSearchList(reportParams),
        getSearchList(caseParams),
      ]);
      if (reportResult.value.code == 200) {
        this.reportList = reportResult.value.data;
      }
      if (caseResult.value.code == 200) {
        this.caseList = caseResult.value.data;
      }
    },
    handleStop() {
      this.websock.close({
        success: (res) => {
          this.loading = false;
          console.log("主动关闭ws成功！", res);
          //关闭之后要重新开启ws
          this.initGptWebsocket();
        },
      });
    },
    handleClickAbleLinkClick(item) {
      this.inputs({
        message: item.title,
        keyword: item.keyword,
        type: 0,
      });
    },
    initGptWebsocket() {
      this.connecting = true;
      this.loading = false;
      let requstWsUrl = "";
      if (process.env.NODE_ENV === "development") {
        requstWsUrl = "wss://chatgpt.yl1001.com";
      } else {
        requstWsUrl = "wss://chatgpt.yl1001.com";
      }
      WebsocketHeartbeat({
        miniprogram: wx,
        connectSocketParams: {
          url: requstWsUrl,
        },
        // repeatLimit: 20,
        stream: true,
        pingTimeout: 3600000,
      }).then((task) => {
        this.websock = task;
        task.onOpen = (e) => {
          this.connecting = false;
          this.loading = false;
          //钩子函数
          uni.hideLoading();
          //这条只是提醒消息，不会被记录进消息记录
          if (
            !this.unshiftmsg.find((_item) => {
              return _item.TextType == 50;
            })
          ) {
            this.unshiftmsg.push({
              role: "assistant",
              sendText:
                "我是您的专属智能职业顾问，您可以向我咨询企业管理相关的问题。",
              createTime: new Date(),
              updateTime: "",
              chatmState: 1,
              TextType: 50,
            });
          }
          console.log("open");
        };
        task.onClose = (e) => {
          this.loading = false;
          //钩子函数
          console.log("close");
        };
        task.onError = (e) => {
          //钩子函数
          task.close({
            success(res) {
              console.log("ws错误，关闭此连接！", res);
            },
          });
          this.loading = false;
          console.log("onError：", e);
          uni.hideLoading();
          // uni.showToast({
          //   title: "连接小览失败！正在重试！",
          //   icon: "none",
          // });
          setTimeout(() => {
            this.initGptWebsocket();
          }, 5000);
        };
        task.onMessage = (data) => {
          //钩子函数
          try {
            var res = JSON.parse(data.data);
          } catch (error) {
            console.log(error, data);
            this.loading = false;
          }
          if (res == "err") {
            this.loading = false;
            return;
          }
          let msg = res.choices && res.choices[0];
          if (msg.finish_reason == "done") {
            this.loading = false;
            this.isContinue = false;
            this.isStoped = true;
            this.uploadChatRecord(this.unshiftmsg[this.unshiftmsg.length - 1]);
            if (this.reportList.length) {
              let asistentData = {
                role: "assistant",
                sendText: "",
                createTime: new Date(),
                updateTime: "",
                chatmState: 1,
                TextType: 1,
              };
              this.unshiftmsg.push(asistentData);
              this.unshiftmsg[this.unshiftmsg.length - 1].elanContent =
                this.reportList;
              this.reportList = {};

              this.uploadChatRecord(asistentData);
            }
            if (this.caseList.length) {
              let asistentData = {
                role: "assistant",
                sendText: "",
                createTime: new Date(),
                updateTime: "",
                chatmState: 1,
                TextType: 2,
              };
              this.unshiftmsg.push(asistentData);
              this.unshiftmsg[this.unshiftmsg.length - 1].elanContent =
                this.caseList;
              this.caseList = {};
              setTimeout(() => {
                this.uploadChatRecord(asistentData);
              }, 300);
            }
            //不能统一用一个 因为这里也插入了要重新刷新选择器
            // const selector = "msg" + (this.unshiftmsg.length - 1);
            // setTimeout(() => {
            //   this.scrollToViewSelector = selector;
            //   console.log("滚动了，并且选择器是：", this.scrollToViewSelector);
            // }, 300);
            return;
          }
          let currentMsg = msg.delta.content || "";
          this.unshiftmsg[this.unshiftmsg.length - 1].sendText += currentMsg;
          // gpt 逐字发送的时候 要判断是否需要自动滚到底部
          this.autoScrollLastView(currentMsg);
        };
        task.onReconnect = () => {
          //钩子函数
          // uni.showLoading({ mask: true, title: "正在连接小览中" });
          this.connecting = true;
          this.loading = false;
          console.log("reconnect...");
        };
      });
    },
    handleToDetail(item) {
      let params = {
        mpaActivityId: item.activityIdCode,
        activityName: item.activityName,
        activityDesc: item.activityIntroduce,
        browsePersonId: this.personId,
        moduleType: "OCCUPATION_MODULE_TYPE",
      };
      reqAppAddBrowseRecord(params, this.personId);
      uni.navigateTo({
        url: "/pagesSub/companyCenter/case/detail?id=" + item.activityIdCode,
      });
    },
    changeTime(date) {
      return dateTime.dateTime1(date);
    },
    // 进行图片的预览
    previewImg(e) {
      let index = 0;
      for (let i = 0; i < this.imgMsg.length; i++) {
        if (this.imgMsg[i] == e) {
          index = i;
        }
      }

      // 预览图片
      uni.previewImage({
        current: index,
        urls: this.imgMsg,
        longPressActions: {
          itemList: ["发送给朋友", "保存图片", "收藏"],
          success: function (data) {
            console.log(
              "选中了第" +
                (data.tapIndex + 1) +
                "个按钮,第" +
                (data.index + 1) +
                "张图片"
            );
          },
          fail: function (err) {
            console.log(err.errMsg);
          },
        },
      });
    },
    //音频播放
    // playVoice(e) {
    //   innerAudioContext.src = e;
    //   innerAudioContext.onPlay(() => {
    //     console.log("开始播放");
    //   });
    // },
    //地图定位
    covers(e) {
      let map = [
        {
          latitude: e.latitude,
          longitude: e.longitude,
          iconPath: "../../../static/logo.png",
        },
      ];
      return map;
    },
    //跳转地图信息
    openLocation(e) {
      uni.openLocation({
        latitude: e.latitude,
        longitude: e.longitude,
        name: e.name,
        address: e.address,
        success: function () {
          console.log("success");
        },
      });
    },
    //输入框高度
    heights(e) {
      console.log("高度:", e);
      this.inputh = e;
      this.inputAreaHeight = e;
      // this.goBottom();
    },
    submitElementRect(e) {
      console.log("submitElementRect:");
      console.log(e);
      this.inputAreaTop = e.top;
    },

    // 滚动到底部
    goBottom() {
      const selector = "msg" + (this.unshiftmsg.length - 1);
      setTimeout(() => {
        this.scrollToViewSelector = selector;
        console.log("滚动了，并且选择器是：", this.scrollToViewSelector);
      }, 300);
    },

    autoScrollLastView(currentMsg) {
      const selector = "msg" + (this.unshiftmsg.length - 1);
      uni
        .createSelectorQuery()
        .select("#" + selector)
        .boundingClientRect((data) => {
          this.recordLastMsgHeight.preHeight =
            this.recordLastMsgHeight.newHeight;
          this.recordLastMsgHeight.newHeight = data.height;
        })
        .exec();
      if (
        this.recordLastMsgHeight.preHeight ==
          this.recordLastMsgHeight.newHeight &&
        !(currentMsg + "").includes("\n")
      ) {
        // 消息的高度没有增加并且没有换行符号
        return;
      }
      //this.isCalculating = true;
      const lastViewSelector = "lastView";
      const query = uni.createSelectorQuery().in(this);
      query
        .select("#" + lastViewSelector)
        .boundingClientRect((data) => {
          var lastViewTop = data.top;
          if (lastViewTop > this.inputAreaTop + 11 + uni.upx2px(32) * 2.5) {
            // this.isCalculating = false;
          } else {
            // 先设置 空字符串，再设置描点
            this.scrollToViewSelector = "";
            setTimeout(() => {
              this.scrollToViewSelector = lastViewSelector;
              //  console.log("autoScrollLastView 滚动了，并且选择器是：", this.scrollToViewSelector);
              // this.isCalculating = false;
            }, 10);
          }
        })
        .exec();
    },
  },
};
</script>

<style lang="scss">
.content {
  position: relative;
  background-color: #f7f8fa;
}

.chat {
  display: flex;
  flex-direction: column;
  position: relative;
  max-height: calc(100vh - 351rpx);
  width: calc(100vw);
  padding-top: 170rpx;
  padding-bottom: 180rpx;
  overflow: hidden;
  background-color: #f4f6f8;
  .usualProblemListContainer {
    display: flow-root;
    padding: 24rpx;
    margin: 28rpx 24rpx 26rpx;
    background: #ffffff;
    border-radius: 16rpx;
    .problemTips {
      margin-bottom: 20rpx;
    }
    .clickAbleLink {
      display: flex;
      align-items: flex-start;
      font-size: 32rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #222222;
      margin-bottom: 20rpx;
      .dotContainer {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 38rpx;
        .problemDot {
          width: 12rpx;
          min-width: 12rpx;
          height: 12rpx;
          background: #ffd2c4;
          margin-right: 14rpx;
          border-radius: 50%;
        }
      }
    }
    .reloadLinks {
      display: flex;
      justify-content: center;
      font-size: 30rpx;
      color: orangered;
      margin-top: 20rpx;
      .reloadIconContainer {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 16rpx;
        width: 42rpx;
        height: 42rpx;
      }
    }
  }
  .chat-ls {
    padding: 0 24rpx;
    .chat-time {
      font-size: 24rpx;
      color: rgba(39, 40, 50, 0.3);
      line-height: 34rpx;
      padding: 10rpx 0rpx;
      text-align: center;
    }
    .msg-m {
      display: flex;
      padding: 20rpx 0;
      .user-img {
        flex: none;
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
      }
      .message {
        flex: none;
        max-width: 494rpx;
      }
      .msg-text {
        font-size: 32rpx;
        color: rgba(39, 40, 50, 1);
        line-height: 44rpx;
        padding: 16rpx 16rpx 20rpx 20rpx;
        .gptText {
          -moz-user-select: text;
          -ms-user-select: text;
          user-select: text;
        }
      }
      .msg-report {
        font-size: 32rpx;
        color: rgba(39, 40, 50, 1);
        line-height: 44rpx;
        padding: 4rpx 16rpx;
        background-color: white;
        margin-left: 16rpx;
        background-color: #fff;
        border-radius: 0rpx 12rpx 12rpx 12rpx;
      }
      .msg-case {
        font-size: 32rpx;
        color: rgba(39, 40, 50, 1);
        line-height: 44rpx;
        padding: 4rpx 16rpx;
        background-color: white;
        margin-left: 16rpx;
        background-color: #fff;
        border-radius: 0rpx 12rpx 12rpx 12rpx;
      }

      .msg-img {
        max-width: 400rpx;
        border-radius: 20rpx;
      }

      .msg-map {
        background: #fff;
        width: 464rpx;
        height: 284rpx;
        overflow: hidden;

        .map-name {
          font-size: 32rpx;
          color: rgba(39, 40, 50, 1);
          line-height: 44rpx;
          padding: 18rpx 24rpx 0 24rpx;
          //下面四行是单行文字的样式
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
        }

        .map-address {
          font-size: 24rpx;
          color: rgba(39, 40, 50, 0.4);
          padding: 0 24rpx;
          //下面四行是单行文字的样式
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
        }

        .map {
          padding-top: 8rpx;
          width: 464rpx;
          height: 190rpx;
        }
      }

      .voice {
        // width: 200rpx;
        min-width: 100rpx;
        max-width: 400rpx;
      }

      .voice-img {
        width: 28rpx;
        height: 36rpx;
      }
    }

    .msg-left {
      flex-direction: row;
      .msg-text {
        font-size: 32rpx;
        margin-left: 16rpx;
        background-color: #fff;
        border-radius: 0rpx 12rpx 12rpx 12rpx;
        -moz-user-select: text;
        -ms-user-select: text;
        user-select: text;
      }

      .ms-img {
        margin-left: 16rpx;
      }

      .msh-map {
        margin-left: 16rpx;
        border-radius: 0rpx 20rpx 20rpx 20rpx;
      }

      .voice {
        text-align: right;
      }

      .voice-img {
        float: left;
        transform: rotate(180deg);
        width: 28rpx;
        height: 36rpx;
        padding-bottom: 4rpx;
      }
    }

    .msg-right {
      flex-direction: row-reverse;

      .msg-text {
        margin-right: 16rpx;
        background-color: #ffe7e3;
        border-radius: 12rpx 0 12rpx 12rpx;
        color: #333333;
        -moz-user-select: text;
        -ms-user-select: text;
        user-select: text;
      }

      .ms-img {
        margin-right: 16rpx;
      }

      .msh-map {
        margin-left: 16rpx;
        border-radius: 20rpx 0rpx 20rpx 20rpx;
      }

      .voice {
        text-align: left;
      }

      .voice-img {
        float: right;
        padding: 4rpx;
        width: 28rpx;
        height: 36rpx;
      }
    }
  }
}
.android-chat {
  padding-top: 130rpx;
  padding-bottom: 120rpx;
  max-height: calc(100vh - 290rpx) !important;
  // max-height: calc(100vh - 240rpx) !important;
}
.rank {
  // margin-top: 20rpx;
  .addonTips {
    margin: 0rpx 0 20rpx;
  }
  &-item {
    display: flex;
    margin: 18rpx 0;
    flex-direction: column;
    padding: 8rpx 8rpx 4rpx 4rpx;
    &-left {
      text-align: center;
      margin-right: 20rpx;
      .icon {
        width: 36rpx;
        height: 58rpx;
      }

      &_bt {
        margin-top: -12rpx;
        .range {
          font-size: 12rpx;
        }
      }
    }
    &-bottom {
      display: flex;
      justify-content: space-between;
    }
    &-title {
      margin-bottom: 15rpx;
    }
    &-des {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      margin-right: 30rpx;
      // height: 68rpx;
      font-size: 26rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 38rpx;
      // margin-top: 4rpx;
    }
    &-img {
      width: 78rpx;
      height: 86rpx;
      border-radius: 8rpx;
    }

    .range {
      &-up {
        color: #ff7777;
      }

      &-down {
        color: #dbac51;
      }
    }

    &-text {
      flex: 1;
      // width: 0;
      max-width: 480rpx;
      overflow-x: hidden;
      word-wrap: break-word; /*强制换行*/
      overflow: hidden; /*超出隐藏*/
      text-overflow: ellipsis; /*隐藏后添加省略号*/
    }

    &-num {
      margin-right: 16rpx;
      width: 44rpx;
      text-align: center;
      font-size: $uni-font-size-base;
      font-weight: 500;
      color: #999999;
    }
  }
}
</style>

